<?php
require_once "../lib/common.php";
$response = array();

if ( ! empty($_POST) ) {
    $user = Login::getLoggedIn();
    if ($user == null) {
        error_die("you are not logged-in");
    }
    if ( isset($_POST['add']) || isset($_POST['quantity']) || isset($_POST['remove'])) {
        if ( ! isset($_POST['book_id']) ) {
            error_die("invalid input");
        }
        $cond = array( 'id' => $_POST['book_id']);
        if ( count(Book::find($cond)) != 1 ) {
            error_die("invalid book");
        }
        unset($cond);

        $item = Cart::find(array("conditions" => array(
            "user_id" => $user->id,
            "book_id" => $_POST['book_id']
            )));
        
        if (isset($_POST['add'])) {
            if ($item) {
             $item->quantity++;
             $item->save();
            } else {
                $item = new Cart();
                $item->book_id = $_POST['book_id'];
                $item->user_id = $user->id;
                $item->quantity = 1;
                $item->save();
            }
        } else if (isset($_POST['quantity'])) {
            if ($item) {
                $item->quantity = (int)$_POST['quantity'];
                $item->save();
            } else {
                $item = new Cart();
                $item->book_id = $_POST['book_id'];
                $item->user_id = $user->id;
                $item->quantity = (int)$_POST['quantity'];
                $item->save();
            }
        } else if (isset($_POST['remove'])) {
            if ($item) {
                $item->delete();
            } else {
                error_die("not in cart");
            }
        }
    } else if ( isset($_POST['clear'])) {
        foreach ($user->carts as $item) {
            $item->delete();
        }
    }
} else {
    $user = Login::getLoggedIn();
    if ($user == null) {
        error_die("access denied");
    }
    $faux = new Cart();
    $response['attributes'] = array_keys(
        $faux->attributes_but(array("book_id","user_id")));
    array_push($response['attributes'],"book");
    array_push($response['attributes'],"user");
    unset($faux);
    $options = array(
        'conditions' => array('user_id'=> $user->id ),
    );
    $cart = Cart::all($options);
    $cart_collection = array();
    foreach ($cart as $item) {
        $attrs = $item->attributes_but(array("book_id","user_id"));
        $attrs['book'] = $item->book->attributes_but(
            array("description","on_stock","category_id","created_at","updated_at"));
        $attrs['user'] = $item->user->attributes_but(array("email"));
        array_push($cart_collection,$attrs);
    }
    $response['collection'] = $cart_collection;
}

if (!empty($response)) {
    echo json_encode($response);
}
?>
